package net.oschina.esb.webmvc.converter;

import net.oschina.esb.webmvc.converter.json.ExtendMappingJackson2HttpMessageConverter;
import net.oschina.esb.webmvc.converter.json.JsonJavascriptAdvice;
import net.oschina.esb.webmvc.converter.json.JsonpAdvice;
import net.oschina.esb.webmvc.converter.json.StringHttpMessageAdvice;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;

import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * 自动注册 Http 消息转换器
 *
 * @author Arvin
 * @time 2017/12/13 9:40
 */
@Import({JsonpAdvice.class, JsonJavascriptAdvice.class, StringHttpMessageAdvice.class})
public class AutoWebmvcHttpMessageConverterConfiguration {

    private static final Log logger = LogFactory.getLog(AutoWebmvcHttpMessageConverterConfiguration.class);

    /**
     * 自定义 HttpMessageConverter
     * https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/#HttpMessageConverters
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(value = HttpMessageConverters.class, search = SearchStrategy.CURRENT)
    public HttpMessageConverters customConverters() {

        logger.info("创建 [HttpMessageConverters], 支持 JSONP, JAVASCRIPT, JSON");

        ExtendMappingJackson2HttpMessageConverter objectHttpMessageConverter = new ExtendMappingJackson2HttpMessageConverter();

        objectHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
        objectHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(
                MediaType.APPLICATION_JSON,
                MediaType.APPLICATION_JSON_UTF8
        ));

        ObjectMapper objectMapper = new ObjectMapper();
        // 序列化时，include规则为：不包含为空字符串，空集合，空数组或null的属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        objectHttpMessageConverter.setObjectMapper(objectMapper);

        return new HttpMessageConverters(objectHttpMessageConverter);
    }
}
